﻿using BlossomiShymae.GrrrLCU;
using Common.Enums;
using Common.Untils;
using HandyControl.Controls;
using LOLApi;
using LOLApi.Models;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Tryit.Views;
using Websocket.Client;

namespace Tryit.ViewModels
{
    public class HomeWindowViewModel : BindableBase
    {
        #region 变量
        private Timer reconnectTimer;
        private bool isReconnecting;//重连标志
        private bool _isFromLoginStatusChanged = false;
        private string _loLClientStatus = "——";
        public string LoLClientStatus
        {
            get
            {
                return _loLClientStatus;
            }
            set
            {
                SetProperty(ref _loLClientStatus, value);
            }
        }
        public WebsocketClient? Client { get; set; }
        /// <summary>
        /// 页面名称
        /// </summary>
        private string _page;
        public string Page
        {
            get { return _page; }
            set { SetProperty(ref _page, value); }
        }
        public event Action<bool> LoginStatusChanged;
        /// <summary>
        /// 是否已经登录游戏
        /// </summary>
        private bool _isLogin;
        public bool IsLogin
        {
            get { return _isLogin; }
            set
            {
                if (_isLogin != value)
                {
                    SetProperty(ref _isLogin, value);
                    LoginStatusChanged?.Invoke(_isLogin);
                }
            }
        }
        /// <summary>
        /// 标题名称
        /// </summary>
        private string _title = "Tryit";
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }
        /// <summary>
        /// 收缩或展开按钮名称
        /// &#xe665;为收缩
        /// &#xe668;为展开
        /// </summary>
        private string _expandText;
        public string ExpandText
        {
            get { return _expandText; }
            set { SetProperty(ref _expandText, value); }
        }
        /// <summary>
        /// 是否已经收缩
        /// </summary>
        private bool _isClapsed;
        public bool IsClapsed
        {
            get { return _isClapsed; }
            set { SetProperty(ref _isClapsed, value); }
        }
        /// <summary>
        /// 侧边栏宽度,默认150
        /// </summary>
        private string _sidebarWidth;
        public string SidebarWidth
        {
            get { return _sidebarWidth; }
            set { SetProperty(ref _sidebarWidth, value); }
        }
        /// <summary>
        /// 展开或收缩按钮命令
        /// </summary>
        private DelegateCommand _expandCommand;
        public DelegateCommand ExpandCommand
        {
            get => new DelegateCommand(new System.Action(() =>
            {
                if (!IsClapsed)
                {
                    ExpandText = "\xe668";
                    SidebarWidth = "48";
                    IsClapsed = true;
                }
                else
                {
                    ExpandText = "\xe665";
                    SidebarWidth = "150";
                    IsClapsed = false;
                }
            }));
        }
        /// <summary>
        /// 切换导航页面
        /// </summary>
        public DelegateCommand<string> NavagationTo { get; set; }
        /// <summary>
        /// RegionManager导航管理
        /// </summary>
        private readonly IRegionManager _regionManager;

        #endregion
        public HomeWindowViewModel(IRegionManager regionManager)
        {
            InitPara();
            _regionManager = regionManager;
            Task.Run(async () =>
            {
                await InitializeWebsocket(null);
            });
            LoginStatusChanged += CheckLoginStatusChanged;//事件检测登录状态改变自动切换导航页面
            NavagationTo = new DelegateCommand<string>(Goto);
            SetDefalutPage();
        }
        private async Task InitializeWebsocket(object obj)
        {
            while (true)
            {
                try
                {
                    var client = Connector.CreateLcuWebsocketClient();
                    client.DisconnectionHappened.Subscribe(OnDisconnection);
                    await client.Start();
                    client.Send(new EventMessage(EventRequestType.Subscribe, EventKinds.OnJsonApiEvent));
                    client.EventReceived.Subscribe(msg =>
                     {
                         if (msg?.Data?.Uri == "/lol-gameflow/v1/gameflow-phase")
                         {
                             var phase = msg?.Data.Data.ToString();
                             SwithStatus(phase);
                         }
                     });
                    Client = client;
                    HttpClient LcuClient = new LcuClient()._httpClient;
                    Account.Summoner = await GetInfo.GetSummonerAsync(LcuClient);
                    Account.Champions = await GetInfo.GetChampionInfos(LcuClient);
                    if (Account.Summoner != null && Account.Champions != null) IsLogin = true;
                    string file = Path.Combine(Environment.CurrentDirectory, "settings.josn");
                    if (File.Exists(file))
                    {
                        string josnString = File.ReadAllText(file);
                        Account.AllSettings = JsonSerializer.Deserialize<AllSettings>(josnString);
                    }
                    return;
                }
                catch (Exception e)
                {
                    Log.WriteLog("websocket连接失败！");

                }
                await Task.Delay(5000);
            }
        }

        private async void SwithStatus(string phase)
        {
            switch (phase)
            {
                case "ReadyCheck":
                    LoLClientStatus = "找到对局";
                    if (Account.AllSettings != null)
                    {
                        if (Account.AllSettings.AutoAcceptGame)
                        {
                            HttpClient LcuClient = new LcuClient()._httpClient;
                            await GetInfo.AutoAcceptGame(LcuClient);
                        }
                    }
                    break;
                case "ChampSelect":
                    LoLClientStatus = "英雄选择中";
                    break;
                case "None":
                    LoLClientStatus = "大厅中或正在创建对局";
                    break;
                case "Reconnect":
                    LoLClientStatus = "游戏中,等待重新连接";
                    break;
                case "Lobby":
                    LoLClientStatus = "房间中";
                    break;
                case "Matchmaking":
                    LoLClientStatus = "匹配中";
                    break;
                case "InProgress":
                    LoLClientStatus = "游戏中";
                    break;
                case "GameStart":
                    LoLClientStatus = "游戏开始了";
                    break;
                case "WaitingForStats":
                    LoLClientStatus = "等待结算界面";
                    break;
                case "PreEndOfGame":
                    break;
                case "EndOfGame":
                    if (Account.AllSettings != null)
                    {
                        if (Account.AllSettings.AutoNextGame)
                        {
                            HttpClient LcuClient = new LcuClient()._httpClient;
                            await GetInfo.AutoNextGame(LcuClient);
                        }
                    }
                    break;
                default:
                    LoLClientStatus = "未知状态" + phase;
                    break;
            }

        }
        private async void OnDisconnection(DisconnectionInfo info)
        {
            try
            {
                if (isReconnecting) return;// 如果正在重连，直接返回
                isReconnecting = true; // 设置重连标志
                Client?.Dispose();
                Client = null;
                if (Account.Summoner != null && !ProcessFinder.IsPortOpen())
                {
                    Account.Summoner = null;
                    Account.Champions = null;
                    LoLClientStatus = "——";
                    IsLogin = false;
                }

                // 使用定时器来控制重连的频率
                if (reconnectTimer == null)
                {
                    reconnectTimer = new Timer(async _ =>
                    {
                        try
                        {
                            await InitializeWebsocket(null);
                        }
                        catch (Exception e)
                        {
                            // 处理异常
                        }
                        finally
                        {
                            reconnectTimer.Dispose();
                            reconnectTimer = null;
                            isReconnecting = false; // 重连完成后重置标志
                        }
                    }, null, 2000, Timeout.Infinite);
                }
            }
            catch (Exception e) { Log.WriteLog("重连失败！"); }
        }

        private void CheckLoginStatusChanged(bool obj)
        {
            _isFromLoginStatusChanged = true;
            NavagationTo.Execute(Page);
            _isFromLoginStatusChanged = false;
        }

        private void SetDefalutPage() //通过ContentRegion管理导航默认初始页面ContactView
        {

            _regionManager.RegisterViewWithRegion("ContentRegion", typeof(Error));//一开始是未登录
            Page = typeof(SummonerInfo).Name.ToString();//默认page为SummonerInfo,无论是否登录
        }
        public void Goto(string page)
        {
            Page = page;
            var navigationParameters = new NavigationParameters();
            if (_isFromLoginStatusChanged) navigationParameters.Add("shouldReload", true);
            if (IsLogin)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    _regionManager.RequestNavigate("ContentRegion", Page, navigationParameters);
                });
            }
            else
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (Page == Enum.GetName(typeof(NavigationParm), 2) || Page == Enum.GetName(typeof(NavigationParm), 4))
                    {
                        _regionManager.RequestNavigate("ContentRegion", Page, navigationParameters);
                    }
                    else { _regionManager.RequestNavigate("ContentRegion", "Error", navigationParameters); }
                });
            }
        }

        private void InitPara()
        {
            ExpandText = "\xe665";
            SidebarWidth = "150";
        }


    }
}
